// pages/movie/movie.js
import regeneratorRuntime from '../../utils/runtime.js'
import MovieService from '../../utils/service/MovieService'

const movieService = new MovieService()

Page({
  /**
   * 页面的初始数据
   */
  data: {},

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    const [top250, comingSoon, inTheaters] = await Promise.all([
      movieService.top250(),
      movieService.comingSoon(),
      movieService.inTheaters()
    ])
    this.processDoubanData(top250, 'top250', '豆瓣Top250')
    this.processDoubanData(comingSoon, 'comingSoon', '即将上映')
    this.processDoubanData(inTheaters, 'inTheaters', '正在热映')
  },

  convertToStarsArray(stars) {
    const num = stars.toString().substring(0, 1)
    const array = []
    for (let i = 1; i <= 5; i++) {
      if (i <= num) {
        array.push(1)
      } else {
        array.push(0)
      }
    }
    return array
  },

  processDoubanData(moviesDouban, settedKey, categoryTitle) {
    const movies = moviesDouban.subjects.map((subject) => {
      let { title } = subject
      if (title.length >= 6) {
        title = `${title.substring(0, 6)}...`
      }
      // [1,1,1,1,1] [1,1,1,0,0]
      const temp = {
        stars: this.convertToStarsArray(subject.rating.stars),
        title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      return temp
    })
    const readyData = {}
    readyData[settedKey] = {
      categoryTitle,
      movies
    }

    this.setData(readyData)
  },

  test() {
    // wx.request({
    //   url: 'http://t.yushu.im/v2/movie/top250?start=0&count=3',
    //   header: {
    //     'content-type': 'application/json'
    //   },
    //   success(res) {
    //     console.log(res.data)
    //   }
    // })
    // console.info(MovieService)
  }
})
